import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
import router from '@/router'

const service = axios.create({
  baseURL: 'http://localhost:8080/',
  withCredentials: true, // 允许发送Cookie
  timeout: 5000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    if(response.data.code===0){
      Message.error(response.data.msg)
    }
     if(response.data.code===2){
      //未登录，跳转到登录页
      Message.error(response.data.msg)
      store.commit('user/removeToken')
      router.push('/login')
    }
    return response.data
  },
  error => {
    console.log(error);
    Message.error(error.response.data.msg)
    //判断token是否过期
    if(error.response.status == 401){
      //清除token，跳转到登录页
      store.$commit('user/removeToken')
      router.push('/login')
    }
    return Promise.reject(error)
  }
)

export default service
